package com.seecen.controller;

import com.seecen.pojo.dto.FeedbackDTO;
import com.seecen.pojo.entity.User;
import com.seecen.service.EmailService;
import com.seecen.service.UserService;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @program: SharkBookkeeping-end
 * @description:
 * @author: XXW
 * @create: 2025-10-17 21:21
 * @version: 1.0
 **/
@RestController
@RequestMapping("/feedback")
@CrossOrigin
@Slf4j
public class FeedbackController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 提交用户反馈（发送邮件）
     * @param token 用户token
     * @param feedbackDTO 反馈信息
     * @return 提交结果
     */
    @PostMapping("/submit")
    public Result submitFeedback(@RequestHeader String token, @RequestBody FeedbackDTO feedbackDTO) {
        try {
            // 验证token
            boolean isExpiration = jwtHelper.isExpiration(token);
            if (isExpiration) {
                return Result.build(null, ResultCode.NOTLOGIN);
            }

            // 获取用户信息
            Long userId = jwtHelper.getUserId(token);
            User user = userService.getById(userId);

            if (user == null) {
                return Result.build(null, ResultCode.USERNAME_ERROR);
            }

            // 设置用户昵称
            String userName = user.getNickname() != null ? user.getNickname() : user.getUsername();
            feedbackDTO.setUserName(userName);

            // 发送邮件
            boolean success = emailService.sendFeedbackEmail(feedbackDTO);

            if (success) {
                log.info("用户反馈提交成功，用户ID：{}，类型：{}", userId, feedbackDTO.getFeedbackType());

                HashMap<String, Object> data = new HashMap<>();
                data.put("message", "感谢您的反馈，我们会尽快处理！");

                return Result.ok(data);
            } else {
                log.error("用户反馈提交失败，用户ID：{}", userId);
                return Result.build(null, ResultCode.FEEDBACK_SEND_ERROR);
            }

        } catch (Exception e) {
            log.error("提交反馈异常：{}", e.getMessage(), e);
            return Result.build(null, ResultCode.FEEDBACK_SEND_ERROR);
        }
    }
}